package com.zengqingfa.sharding.jdbc.demo.service.impl;

import com.zengqingfa.sharding.jdbc.demo.entity.Log;
import com.zengqingfa.sharding.jdbc.demo.mapper.LogMapper;
import com.zengqingfa.sharding.jdbc.demo.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 *
 * @fileName: LogServiceImpl
 * @author: zengqf3
 * @date: 2021-4-1 8:34
 * @description:
 */
@Service
public class LogServiceImpl implements LogService {

    @Autowired
    private LogMapper logMapper;

    public Log getLog1() {
        Log log = new Log();
        log.setCreateTime(LocalDateTime.of(2020, 1, 11, 11, 11, 11));
        log.setName("zengqingfa");
        log.setUpdateTime(LocalDateTime.now());
        log.setValue(233L);
        return log;
    }

    public Log getLog2() {
        Log log2 = new Log();
        log2.setCreateTime(LocalDateTime.of(2021, 1, 11, 11, 11, 11));
        log2.setName("zengqingfa22");
        log2.setUpdateTime(LocalDateTime.now());
        log2.setValue(22L);
        return log2;
    }

    /**
     * 正常情况（一库单表，一库两个表，两库两表）：两条记录都插入
     */
    @Override
    public void insert1() {
        Log log1 = getLog1();
        int insert = logMapper.insert(log1);
        System.out.println(insert);

        Log log2 = getLog2();
        int insert2 = logMapper.insert(log2);
        System.out.println(insert2);
    }

    /**
     * 一库单表(都回滚了)
     */
    @Override
    @Transactional
    public void insert2() {
        Log log1 = getLog1();
        int insert = logMapper.insert(log1);
        System.out.println(insert);

        Log log2 = getLog2();
        int insert2 = logMapper.insert(log2);
        int i = 1 / 0;
        System.out.println(insert2);
    }

    /**
     * 一库两表
     */
    @Override
    @Transactional
    public void insert3() {
        Log log1 = getLog1();
        int insert = logMapper.insert(log1);
        System.out.println(insert);

        Log log2 = getLog2();
        int insert2 = logMapper.insert(log2);
        int i = 1 / 0;
        System.out.println(insert2);
    }

    /**
     * 两库
     */
    @Override
    @Transactional
    public void insert4() {
        Log log1 = getLog1();
        int insert = logMapper.insert(log1);
        System.out.println(insert);

        Log log2 = getLog2();
        int insert2 = logMapper.insert(log2);
        int i = 1 / 0;
        System.out.println(insert2);
    }

    @Override
    public void insert5() {

    }
}
